﻿app.controller('HomeController', function ($scope, ContactsService) {

    $scope.greeting = "ni hoa";

    // guid for current edit
    $scope.currIndex = -1;

    // button text
    $scope.btnAction = "Add a Contact"

    // array used for the view
    // BIND..
    $scope.listContacts = ContactsService.myContacts;

    // READ - fetch data 
    $scope.doFetch = function() {
        console.log("doFetch was fired")
        // call method on the Service, Success & Error funcion
        ContactsService.getContacts().then(function (data) {
            console.log("controller... ", data);
            $scope.listContacts = data;
        }, function () {
            console.log("controller some error occured");
        });
    }
    // call Fetch on page load
    $scope.doFetch();


    // CREATE - add user to FB
    $scope.doAdd = function () {

        // talk to the service....
        var userObj = {};
        userObj.fName = $scope.userFirst;
        userObj.lName = $scope.userLast;
        userObj.uName = $scope.userId;
        console.log("User Details: ", userObj);

        // if there is a ArrIndex, must try edit. Otherwise just add
        if ($scope.currIndex == -1) { // Adding...
            ContactsService.createContact(userObj).then(function () {
                // success logic
                console.log("then data reloved... ");
            }, function () {
                console.log("Error occured!");
            })
        } else { // Editing...
            // $scope.currGuid
            // obj to post
            ContactsService.updateContact(userObj, $scope.currIndex).then(function () {
                // success logic
                console.log("then data reloved... ");
            }, function () {
                console.log("Error occured!");
            });
            // reset to 'Adding' state
            $scope.btnAction = "Add a Contact";
            $scope.currIndex = -1;
        }
        
    }


    // UPDATE / Edit

    $scope.startEdit = function (aid) {
        $scope.currIndex = aid; // array position
        console.log("Curr GUID to edit: ", $scope.currGuid);
        $scope.userFirst = $scope.listContacts[aid].fName;
        $scope.userLast = $scope.listContacts[aid].lName;
        $scope.userId = $scope.listContacts[aid].uName;
        $scope.btnAction = "Save Changes";

    }



});